package top.frsf.rpc.registry.impl;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import top.frsf.rpc.constants.RedisConstants;
import top.frsf.rpc.entity.ServiceInstance;
import top.frsf.rpc.registry.ServiceRegistry;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Redis 服务注册中心
 *
 * @author He Kuntao
 * @since 2025/7/11 15:03
 */
@Slf4j
@RequiredArgsConstructor
public class RedisServiceRegistry implements ServiceRegistry {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void register(String serviceName, ServiceInstance instance) {
        stringRedisTemplate.opsForSet().add(getServiceKey(serviceName), JSONUtil.toJsonStr(instance));
        log.info("Register service: {} -> {}", serviceName, instance);
    }

    @Override
    public void unregister(String serviceName, String serviceAddress) {
        stringRedisTemplate.opsForSet().remove(getServiceKey(serviceName), serviceAddress);
        log.info("Unregister service: {} -> {}", serviceName, serviceAddress);
    }

    @Override
    public List<ServiceInstance> discover(String serviceName) {
        Set<String> members = stringRedisTemplate.opsForSet().members(getServiceKey(serviceName));
        return members == null ? Collections.emptyList() : members.stream()
                .map(json -> JSONUtil.toBean(json, ServiceInstance.class))
                .collect(Collectors.toList());
    }

    /**
     * 获取服务注册 Redis key
     *
     * @param serviceName 服务名称
     * @return Redis key
     */
    private String getServiceKey(String serviceName) {
        return String.format(RedisConstants.REDIS_SERVICE_KEY, serviceName);
    }

}


